<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import api from '@/api/modules/theme'
import apiUser from '@/api/modules/useranks'
import { ElMessage, ElMessageBox } from 'element-plus'
import { watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

defineOptions({
  name: 'PagesExampleMenuList',
})
const { pagination, getParams, onSizeChange, onCurrentChange } = usePagination()

const router = useRouter()

// 大赛主题选项
const themeTitleOptions = ref([
  { value: '1', label: '校徽' },
  { value: '2', label: '周边' },
])
// 表格是否自适应高度
const tableAutoHeight = ref(false)

// 列表
const loading = ref(false)
const dataList = ref([])
const route = useRoute()

// 大赛主题映射
const getThemeTitleLabel = (value: string) => {
  const map: Record<string, string> = {
    1: '校徽',
    2: '周边',
  }
  return map[value] || '未知'
}

// 大赛类型映射
const getThemeTypeLabel = (value: string) => {
  const map: Record<string, string> = {
    0: '平台',
    1: '学校',
  }
  return map[value] || '未知'
}

const schoolOptions = ref<SchoolOption[]>([]) // 加载学校列表
interface SchoolOption {
  label: string
  value: number
}

watch(
  () => route.query.timestamp,
  () => {
    if (route.name === 'PagesExampleMenuList') {
      getDataList()
    }
  },
)
onMounted(() => {
  loadSchoolOptions()
  getDataList()
})
// 搜索
const searchDefault = {
  themeName: '',
  schoolName: '',
  themeTitle: '',
}
const search = ref({ ...searchDefault })
function searchReset() {
  Object.assign(search.value, searchDefault)
}

// 初始化
function getDataList() {
  loading.value = true
  const params = {
    themeName: search.value.themeName,
    schoolName: search.value.schoolName,
    themeTitle: search.value.themeTitle,
    ...(getParams()),
  }
  api.list(params).then((res: any) => {
    loading.value = false
    dataList.value = res.rows
    pagination.value.total = res.total
  })
}

// 新增
function onCreate(row?: any) {
  router.push({
    name: 'themeCreate',
    query: {
      parentId: row.id,
    },
  })
}

// 修改
function onEdit(row: any) {
  router.push({
    name: 'themeEdit',
    params: {
      id: row.themeId,
    },
    query: {
      mySelf: row.mySelf, // 传递 mySelf 字段
    },
  })
}

function onDel(row: any) {
  ElMessageBox.confirm(`确认删除「${row.themeName}」吗？`, '确认信息').then(() => {
    api.delete(Number(row.themeId)).then((res: any) => {
      if (res.code === 200) {
        getDataList()
        ElMessage.success({
          message: '删除成功',
        })
      }
    })
  }).catch(() => {})
}
// 每页数量切换
function sizeChange(size: number) {
  onSizeChange(size).then(() => getDataList())
}

// 当前页码切换（翻页）
function currentChange(page = 1) {
  onCurrentChange(page).then(() => getDataList())
}

// 照片预览
function previewImage(url: string) {
  window.open(url, '_blank')
}

// 查询学校列表
async function loadSchoolOptions() {
  try {
    const res = await apiUser.getSchoolList()
    schoolOptions.value = res.data.map((item: any) => ({
      label: item.schoolName,
      value: item.schoolId,
    }))
  }
  catch (error) {
    console.error('加载失败', error)
  }
}

function viewOpusList(row: any) {
  router.push({
    name: 'opus',
    query: {
      themeName: row.themeName,
    },
  })
}
</script>

<template>
  <div :class="{ 'absolute-container': tableAutoHeight }">
    <FaPageHeader title="主题大赛管理" class="mb-0" />
    <FaPageMain :class="{ 'flex-1 overflow-auto': tableAutoHeight }" :main-class="{ 'flex-1 flex flex-col overflow-auto': tableAutoHeight }">
      <FaSearchBar :show-toggle="false">
        <template #default>
          <ElForm :model="search" size="default" label-width="100px" inline-message inline class="search-form">
            <ElFormItem label="大赛名称">
              <ElInput v-model="search.themeName" placeholder="请输入大赛名称" clearable style="width: 150px" @keydown.enter="currentChange()" @clear="currentChange()" />
            </ElFormItem>
            <ElFormItem v-auth="'system:school:select'" label="学校">
              <el-select v-model="search.schoolName" style="width: 150px" filterable placeholder="请选择学校">
                <el-option
                  v-for="item in schoolOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                />
              </el-select>
            </ElFormItem>
            <ElFormItem label="大赛主题">
              <ElSelect v-model="search.themeTitle" style="width: 150px" placeholder="请选择大赛主题" clearable @clear="currentChange()">
                <ElOption
                  v-for="item in themeTitleOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem>
              <ElButton @click="searchReset(); currentChange()">
                重置
              </ElButton>
              <ElButton v-auth="'system:theme:list'" type="primary" @click="currentChange()">
                <template #icon>
                  <FaIcon name="i-ep:search" />
                </template>
                筛选
              </ElButton>
            </ElFormItem>
          </ElForm>
        </template>
      </FaSearchBar>
      <ElDivider border-style="dashed" />
      <FaPageMain :class="{ 'flex-1 overflow-auto': tableAutoHeight }" :main-class="{ 'flex-1 flex flex-col overflow-auto': tableAutoHeight }">
        <ElSpace>
          <ElButton v-auth="'system:theme:add'" type="primary" size="default" @click="onCreate">
            <template #icon>
              <FaIcon name="i-ep:plus" />
            </template>
            新增大赛
          </ElButton>
        </ElSpace>
        <ElTable v-loading="loading" class="mt-4" :data="dataList" row-key="id" stripe highlight-current-row default-expand-all border height="100%">
          <ElTableColumn prop="themeName" label="大赛名称" />
          <ElTableColumn prop="schoolName" label="归属学校" />
          <ElTableColumn prop="themeTitle" label="大赛主题">
            <template #default="scope">
              {{ getThemeTitleLabel(scope.row.themeTitle) }}
            </template>
          </ElTableColumn>
          <ElTableColumn label="大赛宣传图">
            <template #default="scope">
              <div class="table-image-preview">
                <img :src="scope.row.themeUrl" alt="大赛宣传图" style="max-height: 100px;" @click="previewImage(scope.row.themeUrl)">
              </div>
            </template>
          </ElTableColumn>
          <ElTableColumn prop="expectStartTime" label="开始时间" />
          <ElTableColumn prop="themeType" label="大赛类型">
            <template #default="scope">
              {{ getThemeTypeLabel(scope.row.themeType) }}
            </template>
          </ElTableColumn>
          <ElTableColumn label="操作" width="200" align="center" fixed="right">
            <template #default="scope">
              <ElSpace>
                <ElButton v-auth="'system:opus:list'" type="primary" size="small" plain @click="viewOpusList(scope.row)">
                  查看作品
                </ElButton>
                <ElButton v-auth="'system:theme:edit'" type="primary" size="small" plain @click="onEdit(scope.row)">
                  {{ scope.row.mySelf === 'true' ? '编辑' : '查看' }}
                </ElButton>
                <ElButton v-auth="'system:theme:edit'" type="primary" size="small" plain @click="onDel(scope.row)">
                  删除
                </ElButton>
              </ElSpace>
            </template>
          </ElTableColumn>
        </ElTable>
        <ElPagination style="margin-top: 20px" :current-page="pagination.page" :total="pagination.total" :page-size="pagination.size" :page-sizes="pagination.sizes" :layout="pagination.layout" :hide-on-single-page="false" class="pagination" background @current-change="currentChange" @size-change="sizeChange" />
      </FaPageMain>
    </fapagemain>
  </div>
</template>

<style scoped>
.absolute-container {
  position: absolute;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}
</style>
